package framelib.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * Title:AbsController
 * Description:
 * @Create_by:Vince Yu
 * @Create_date:2012-5-4
 * @Last_Edit_By:
 * @Edit_Description
 * @version:ShareWithUs 1.0
 * 
 */
public abstract class AbsController {

	private static WebApplicationContext wac = null;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
	}

	protected Object getBean(String name, HttpServletRequest request) {
		ServletContext context = request.getSession().getServletContext();
		WebApplicationContext webApplicationContext = this.getWebApplicationContext(context);
		return webApplicationContext.getBean(name);
	}

	/**
	 * web环境下运行时获取Spring的WebApplicationContext
	 * 
	 * @param context
	 *            ServletContext
	 * @return WebApplicationContext
	 */
	public synchronized WebApplicationContext getWebApplicationContext(ServletContext context) {
		if (context == null) {
			return null;
		}
		if (wac == null) {
			wac = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		}
		return wac;
	}

}
